package edu.xhu.utils.common;

import edu.xhu.model.search.pojos.TrieNode;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 热搜联想词工具类
 */
public class SearchPrefixUtil {
    /**
     * 根节点
     */
    private final static TrieNode root = new TrieNode();

    /**
     * 同步锁保证线程安全
     */
    private final static ReentrantLock syncLock = new ReentrantLock();

    // 插入一个单词到前缀树中
    public static void insertWord(String word) {
        syncLock.lock();

        TrieNode node = root;
        for (char ch : word.toCharArray()) {
            node.children.putIfAbsent(ch, new TrieNode());
            node = node.children.get(ch);
        }
        node.isEndOfWord = true;

        syncLock.unlock();
    }


    // 查找所有以给定前缀开始的单词
    public static List<String> searchByPrefix(String prefix) {
        syncLock.lock();

        List<String> results = new ArrayList<>();
        TrieNode node = root;

        for (char ch : prefix.toCharArray()) {
            node = node.children.get(ch);
            if (node == null) {
                return results;
            }
        }
        findAllWords(node, new StringBuilder(prefix), results);

        syncLock.unlock();
        return results;
    }

    // 辅助函数，递归查找所有从当前节点开始的单词
    private static void findAllWords(TrieNode node, StringBuilder prefix, List<String> results) {
        if (node.isEndOfWord) {
            results.add(prefix.toString());
        }
        for (char ch : node.children.keySet()) {
            findAllWords(node.children.get(ch), prefix.append(ch), results);
            prefix.deleteCharAt(prefix.length() - 1);
        }
    }


    // 删除一个单词从前缀树中
    public static boolean deleteWord(String word) {
        syncLock.lock();
        boolean flag = delete(root, word, 0);
        syncLock.unlock();

        return flag;
    }


    private static boolean delete(TrieNode current, String word, int index) {
        if (index == word.length()) {
            if (!current.isEndOfWord) {
                return false; // 单词不存在
            }
            current.isEndOfWord = false; // 将单词的结尾标志设为 false
            return current.children.isEmpty(); // 如果没有子节点，则可以删除
        }

        char ch = word.charAt(index);
        TrieNode node = current.children.get(ch);
        if (node == null) {
            return false; // 单词不存在
        }

        boolean shouldDeleteCurrentNode = delete(node, word, index + 1);

        if (shouldDeleteCurrentNode) {
            current.children.remove(ch);
            return current.children.isEmpty() && !current.isEndOfWord;
        }

        return false;
    }
}
